import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Badge } from "./ui/badge";
import { Progress } from "./ui/progress";
import { 
  Activity, 
  Database, 
  Users, 
  HardDrive, 
  Cpu, 
  MemoryStick,
  Network,
  Timer,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  CheckCircle,
  Clock
} from "lucide-react";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, AreaChart, Area, BarChart, Bar } from "recharts";
import { useI18n } from "../lib/i18n/context";

interface DatabaseInstance {
  id: string;
  name: string;
  engine: string;
  version: string;
  status: 'running' | 'stopped' | 'pending' | 'maintenance';
  region: string;
  instanceType: string;
  storage: number;
  connections: number;
  cpu: number;
  memory: number;
  createdAt: string;
}

interface PerformanceMonitorProps {
  databases: DatabaseInstance[];
}

// Mock performance data for charts
const generateMockPerformanceData = (type: 'cpu' | 'memory' | 'connections' | 'iops') => {
  const data = [];
  const now = new Date();
  
  for (let i = 23; i >= 0; i--) {
    const time = new Date(now.getTime() - i * 60 * 60 * 1000);
    let value;
    
    switch (type) {
      case 'cpu':
        value = Math.random() * 80 + 10; // 10-90%
        break;
      case 'memory':
        value = Math.random() * 70 + 20; // 20-90%
        break;
      case 'connections':
        value = Math.floor(Math.random() * 50 + 10); // 10-60 connections
        break;
      case 'iops':
        value = Math.floor(Math.random() * 1000 + 100); // 100-1100 IOPS
        break;
      default:
        value = 0;
    }
    
    data.push({
      time: time.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' }),
      value: value
    });
  }
  
  return data;
};

const mockQueryPerformance = [
  { name: 'SELECT', count: 1250, avgTime: 45 },
  { name: 'INSERT', count: 480, avgTime: 12 },
  { name: 'UPDATE', count: 320, avgTime: 28 },
  { name: 'DELETE', count: 85, avgTime: 35 }
];

export function PerformanceMonitor({ databases }: PerformanceMonitorProps) {
  const { t } = useI18n();
  const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('');
  
  const selectedDatabase = databases.find(db => db.id === selectedDatabaseId);
  const runningDatabases = databases.filter(db => db.status === 'running');
  
  const cpuData = generateMockPerformanceData('cpu');
  const memoryData = generateMockPerformanceData('memory');
  const connectionsData = generateMockPerformanceData('connections');
  const iopsData = generateMockPerformanceData('iops');

  const getMetricStatus = (value: number, thresholds: { warning: number; critical: number }) => {
    if (value >= thresholds.critical) return { color: 'text-red-600', bg: 'bg-red-500', status: t.performance.metrics.status.critical };
    if (value >= thresholds.warning) return { color: 'text-orange-600', bg: 'bg-orange-500', status: t.performance.metrics.status.warning };
    return { color: 'text-green-600', bg: 'bg-green-500', status: t.performance.metrics.status.good };
  };

  const formatBytes = (bytes: number) => {
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) return '0 B';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  if (runningDatabases.length === 0) {
    return (
      <div className="space-y-6">
        <h2 className="text-2xl font-bold">{t.performance.title}</h2>
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Database className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-medium mb-2">{t.performance.noRunningInstances}</h3>
            <p className="text-muted-foreground text-center">
              {t.performance.noRunningDescription}
            </p>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold">{t.performance.title}</h2>
        <div className="flex items-center space-x-2">
          <span className="text-sm text-muted-foreground">{t.performance.selectDatabase}</span>
          <Select value={selectedDatabaseId} onValueChange={setSelectedDatabaseId}>
            <SelectTrigger className="w-[250px]">
              <SelectValue placeholder={t.performance.chooseDatabase} />
            </SelectTrigger>
            <SelectContent>
              {runningDatabases.map(db => (
                <SelectItem key={db.id} value={db.id}>
                  <div className="flex items-center space-x-2">
                    <Database className="h-4 w-4" />
                    <span>{db.name}</span>
                    <Badge variant="secondary" className="ml-2 text-xs">
                      {db.engine}
                    </Badge>
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {!selectedDatabase ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Activity className="h-12 w-12 text-muted-foreground mb-4" />
            <h3 className="text-lg font-medium mb-2">{t.performance.selectInstance}</h3>
            <p className="text-muted-foreground text-center">
              {t.performance.selectInstanceDescription}
            </p>
          </CardContent>
        </Card>
      ) : (
        <>
          {/* Database Info Header */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <Database className="h-6 w-6 text-blue-600" />
                  <div>
                    <CardTitle>{selectedDatabase.name}</CardTitle>
                    <p className="text-sm text-muted-foreground">
                      {selectedDatabase.engine} {selectedDatabase.version} • {selectedDatabase.instanceType} • {selectedDatabase.region}
                    </p>
                  </div>
                </div>
                <Badge className="bg-green-500 text-white">
                  <CheckCircle className="h-3 w-3 mr-1" />
                  {t.instances.status.running}
                </Badge>
              </div>
            </CardHeader>
          </Card>

          {/* Key Metrics */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.metrics.cpuUsage}</p>
                    <p className="text-2xl font-bold">{selectedDatabase.cpu}%</p>
                    <div className="flex items-center space-x-1 mt-1">
                      {selectedDatabase.cpu > 70 ? (
                        <TrendingUp className="h-3 w-3 text-red-600" />
                      ) : (
                        <CheckCircle className="h-3 w-3 text-green-600" />
                      )}
                      <span className={`text-xs ${selectedDatabase.cpu > 70 ? 'text-red-600' : 'text-green-600'}`}>
                        {getMetricStatus(selectedDatabase.cpu, { warning: 70, critical: 85 }).status}
                      </span>
                    </div>
                  </div>
                  <Cpu className="h-8 w-8 text-blue-600" />
                </div>
                <Progress value={selectedDatabase.cpu} className="mt-3" />
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.metrics.memoryUsage}</p>
                    <p className="text-2xl font-bold">{selectedDatabase.memory}%</p>
                    <div className="flex items-center space-x-1 mt-1">
                      {selectedDatabase.memory > 80 ? (
                        <TrendingUp className="h-3 w-3 text-orange-600" />
                      ) : (
                        <CheckCircle className="h-3 w-3 text-green-600" />
                      )}
                      <span className={`text-xs ${selectedDatabase.memory > 80 ? 'text-orange-600' : 'text-green-600'}`}>
                        {getMetricStatus(selectedDatabase.memory, { warning: 80, critical: 90 }).status}
                      </span>
                    </div>
                  </div>
                  <MemoryStick className="h-8 w-8 text-purple-600" />
                </div>
                <Progress value={selectedDatabase.memory} className="mt-3" />
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.metrics.activeConnections}</p>
                    <p className="text-2xl font-bold">{selectedDatabase.connections}</p>
                    <div className="flex items-center space-x-1 mt-1">
                      <Users className="h-3 w-3 text-blue-600" />
                      <span className="text-xs text-muted-foreground">
                        of 100 max
                      </span>
                    </div>
                  </div>
                  <Users className="h-8 w-8 text-green-600" />
                </div>
                <Progress value={(selectedDatabase.connections / 100) * 100} className="mt-3" />
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.metrics.storageUsed}</p>
                    <p className="text-2xl font-bold">{Math.round(selectedDatabase.storage * 0.7)} GB</p>
                    <div className="flex items-center space-x-1 mt-1">
                      <HardDrive className="h-3 w-3 text-purple-600" />
                      <span className="text-xs text-muted-foreground">
                        of {selectedDatabase.storage} GB
                      </span>
                    </div>
                  </div>
                  <HardDrive className="h-8 w-8 text-orange-600" />
                </div>
                <Progress value={(selectedDatabase.storage * 0.7 / selectedDatabase.storage) * 100} className="mt-3" />
              </CardContent>
            </Card>
          </div>

          {/* Performance Charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* CPU Usage Over Time */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Cpu className="h-5 w-5" />
                  <span>{t.performance.metrics.charts.cpu24h}</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={200}>
                  <AreaChart data={cpuData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <Tooltip formatter={(value) => [`${Number(value).toFixed(1)}%`, 'CPU Usage']} />
                    <Area type="monotone" dataKey="value" stroke="#8884d8" fill="#8884d8" fillOpacity={0.3} />
                  </AreaChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* Memory Usage Over Time */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <MemoryStick className="h-5 w-5" />
                  <span>{t.performance.metrics.charts.memory24h}</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={200}>
                  <AreaChart data={memoryData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <Tooltip formatter={(value) => [`${Number(value).toFixed(1)}%`, 'Memory Usage']} />
                    <Area type="monotone" dataKey="value" stroke="#82ca9d" fill="#82ca9d" fillOpacity={0.3} />
                  </AreaChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* Connections Over Time */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Users className="h-5 w-5" />
                  <span>{t.performance.metrics.charts.connections24h}</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={200}>
                  <LineChart data={connectionsData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <Tooltip formatter={(value) => [`${value}`, 'Connections']} />
                    <Line type="monotone" dataKey="value" stroke="#ffc658" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* IOPS Over Time */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Activity className="h-5 w-5" />
                  <span>{t.performance.metrics.charts.iops24h}</span>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={200}>
                  <LineChart data={iopsData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="time" />
                    <YAxis />
                    <Tooltip formatter={(value) => [`${value}`, 'IOPS']} />
                    <Line type="monotone" dataKey="value" stroke="#ff7300" strokeWidth={2} />
                  </LineChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

          {/* Query Performance */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Timer className="h-5 w-5" />
                <span>{t.performance.queryPerformance.title}</span>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <ResponsiveContainer width="100%" height={250}>
                    <BarChart data={mockQueryPerformance}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="name" />
                      <YAxis />
                      <Tooltip 
                        formatter={(value, name) => [
                          name === 'count' ? `${value} ${t.performance.queryPerformance.queryCount}` : `${value}ms ${t.performance.queryPerformance.avgResponse}`,
                          name === 'count' ? 'Query Count' : 'Avg Response Time'
                        ]}
                      />
                      <Bar dataKey="count" fill="#8884d8" />
                    </BarChart>
                  </ResponsiveContainer>
                </div>
                <div className="space-y-4">
                  <h4 className="font-medium">Query Statistics</h4>
                  {mockQueryPerformance.map((query, index) => (
                    <div key={query.name} className="flex items-center justify-between p-3 border rounded-lg">
                      <div>
                        <p className="font-medium">{query.name}</p>
                        <p className="text-sm text-muted-foreground">{query.count} {t.performance.queryPerformance.queryCount}</p>
                      </div>
                      <div className="text-right">
                        <p className="font-medium">{query.avgTime}ms</p>
                        <p className="text-xs text-muted-foreground">{t.performance.queryPerformance.avgResponse}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Additional Metrics */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center space-x-3">
                  <Network className="h-8 w-8 text-blue-600" />
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.queryPerformance.networkIO}</p>
                    <p className="font-medium">↑ {formatBytes(1250000)}/s</p>
                    <p className="font-medium">↓ {formatBytes(850000)}/s</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center space-x-3">
                  <Clock className="h-8 w-8 text-green-600" />
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.queryPerformance.avgQueryTime}</p>
                    <p className="text-xl font-bold">32ms</p>
                    <p className="text-xs text-green-600">↓ 12% from yesterday</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center space-x-3">
                  <AlertTriangle className="h-8 w-8 text-orange-600" />
                  <div>
                    <p className="text-sm text-muted-foreground">{t.performance.queryPerformance.activeAlerts}</p>
                    <p className="text-xl font-bold">2</p>
                    <p className="text-xs text-orange-600">1 warning, 1 info</p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </>
      )}
    </div>
  );
}